import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import { asyncRoutes } from '@/router/index'
import 'nprogress/nprogress.css'

const whiteList = ['/login']
router.beforeEach(async(to, from, next) => {
  const token = store.state.user.token
  NProgress.start()
  if (token) {
    if (!store.state.user.UserInfo.userId) {
      await store.dispatch('user/setalluserinfo')
      const menus = store.state.user.UserInfo.roles.menus
      const routers = asyncRoutes.filter(item => {
        return menus.includes(item.children[0].name)
      })
      router.addRoutes([...routers, { path: '*', redirect: '/404', hidden: true }])
      store.commit('permission/setRoutes', routers)
      next({
        ...to,
        replace: true
      })
    }
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
